package org.linlinjava.litemall.mechanismadmin.web;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.systemConfig.GetRegionService;
import org.linlinjava.litemall.core.systemConfig.SystemConfig;
import org.linlinjava.litemall.core.util.CharUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderHandleOption;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.util.SortUtil;
import org.linlinjava.litemall.mechanismadmin.config.Configure;
import org.linlinjava.litemall.mechanismadmin.util.http.HttpsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

@RestController
@RequestMapping("/mechanismadmin/mobile")
public class MechanismMobileController extends GetRegionService {
    @Autowired
    private LitemallMechanismUserService mechanismUserService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallProductService productService;
    @Autowired
    private LitemallIssueService goodsIssueService;
    @Autowired
    private LitemallGoodsAttributeService goodsAttributeService;
    @Autowired
    private LitemallBrandService brandService;
    @Autowired
    private LitemallCommentService commentService;
    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallCollectService collectService;
    @Autowired
    private LitemallFootprintService footprintService;
    @Autowired
    private LitemallCartService cartService;
    @Autowired
    private LitemallGoodsSpecificationService goodsSpecificationService;
    @Resource
    private PlatformTransactionManager txManager;
    @Autowired
    private LitemallMechanismService mechanismService;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    @Autowired
    LitemallWalletRecordService walletRecordService;
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private LitemallAddressService addressService;

    @GetMapping("/login")
    public Object login( String username ,String password,String openid){

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return ResponseUtil.badArgument();
        }
        List<LitemallMechanismUser> mechanismUserList = mechanismUserService.queryByUsername(username);
        Assert.state(mechanismUserList.size() < 2, "同一个用户名存在两个账户");
        if(mechanismUserList.size() == 0){
            return ResponseUtil.fail(403, "账号不对");
        }
        LitemallMechanismUser mechanismUser = mechanismUserList.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(password, mechanismUser.getPassword())){
            System.out.println(encoder.matches(password, mechanismUser.getPassword()));
            return ResponseUtil.fail(403, "密码不对");
        }

        mechanismUser.setOpenId(openid);
        mechanismUserService.update(mechanismUser);
        return ResponseUtil.ok(mechanismUser);
    }


    @GetMapping("/goods")
    public Object goods(Integer limit) {
        if(limit == null){
          limit = 20;
        }
        Map<String, Object> data = new HashMap<>();
        List<LitemallGoods> hotGoods = goodsService.queryCategory(0, limit, SystemConfig.getCateGoryL2());
        int count  = goodsService.categoryCount(SystemConfig.getCateGoryL2());
        data.put("hotGoods", hotGoods);
        data.put("count", count);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/detail")
    public Object detail(Integer userId, Integer id) {
        if (id == null) {
            return ResponseUtil.badArgument();
        }


        // 商品属性
        Callable<List> goodsAttributeListCallable = new Callable<List>() {
            @Override
            public List call() throws Exception {
                List<LitemallGoodsAttribute> goodsAttributeList = goodsAttributeService.queryByGid(id);
                return goodsAttributeList;
            }
        };

        // 商品规格
        Callable<Object> objectCallable = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Object specificationList = goodsSpecificationService.getSpecificationVoList(id);
                return specificationList;
            }
        };

        // 商品规格对应的数量和价格
        Callable<List> productListCallable = new Callable<List>() {
            @Override
            public List call() throws Exception {
                List<LitemallProduct> productList = productService.queryByGid(id);
                return productList;
            }
        };
        // 商品问题，这里是一些通用问题
        Callable<List> issueCallable = new Callable<List>() {
            @Override
            public List call() throws Exception {
                List<LitemallIssue> issue = goodsIssueService.query();
                return issue;
            }
        };

        //购物车商品数量
        Callable<Integer> lcartCallable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                List<LitemallCart> lcart = cartService.queryByUid(userId);
                int cartGoodsCount = 0;
                for (LitemallCart ct:lcart) {
                    cartGoodsCount+=ct.getNumber();
                }
                return cartGoodsCount;
            }
        };

        // 评论
        Callable<Map> commentsCallable = new Callable<Map>() {
            @Override
            public Map call() throws Exception {
                List<LitemallComment> comments = commentService.queryGoodsByGid(id, 0, 2);
                List<Map<String, Object>> commentsVo = new ArrayList<>(comments.size());
                int commentCount = commentService.countGoodsByGid(id, 0, 2);
                for (LitemallComment comment : comments) {
                    Map<String, Object> c = new HashMap<>();
                    c.put("id", comment.getId());
                    c.put("addTime", comment.getAddTime());
                    c.put("content", comment.getContent());
                    LitemallUser user = userService.findById(comment.getUserId());
                    c.put("nickname", user.getNickname());
                    c.put("avatar", user.getAvatar());
                    c.put("picList", comment.getPicUrls());
                    commentsVo.add(c);
                }
                Map<String, Object> commentList = new HashMap<>();
                commentList.put("count", commentCount);
                commentList.put("data", commentsVo);
                return commentList;
            }
        };

        // 用户收藏
        Callable<Integer> userHasCollectCallable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int userHasCollect = 0;
                if (userId != null) {
                    userHasCollect = collectService.count(userId, id);
                }
                return userHasCollect;
            }
        };

        // 记录用户的足迹
        Callable footCallable = new Callable() {
            @Override
            public Object call() throws Exception {
                if (userId != null) {
                    LitemallFootprint footprint = new LitemallFootprint();
                    footprint.setAddTime(LocalDateTime.now());
                    footprint.setUserId(userId);
                    footprint.setGoodsId(id);
                    footprint.setMechanismType(true);
                    footprintService.add(footprint);
                }
                return null;
            }
        };

        FutureTask<List> goodsAttributeListTask= new FutureTask<>(goodsAttributeListCallable);
        FutureTask<Object> objectCallableTask = new FutureTask<>(objectCallable);
        FutureTask<List> productListCallableTask = new FutureTask<>(productListCallable);
        FutureTask<List> issueCallableTask = new FutureTask<>(issueCallable);
        FutureTask<Map> commentsCallableTsk = new FutureTask<>(commentsCallable);
        FutureTask<Integer> lcartTask= new FutureTask<>(lcartCallable);
        FutureTask<Integer> userHasCollectCallableTask = new FutureTask<>(userHasCollectCallable);
        FutureTask footCallableTask = new FutureTask(footCallable);


        new Thread(goodsAttributeListTask).start();
        new Thread(objectCallableTask).start();
        new Thread(productListCallableTask).start();
        new Thread(issueCallableTask).start();
        new Thread(commentsCallableTsk).start();
        new Thread(lcartTask).start();
        new Thread(userHasCollectCallableTask).start();
        new Thread(footCallableTask).start();

        // 商品信息
        LitemallGoods info = goodsService.findById(id);
        // 商品品牌商
        LitemallBrand brand = brandService.findById(info.getBrandId());
        Map<String, Object> data = new HashMap<>();
        data.put("info", info);
        data.put("brand", brand);
        try {
            data.put("userHasCollect", userHasCollectCallableTask.get());
            data.put("issue", issueCallableTask.get());
            data.put("comment", commentsCallableTsk.get());
            data.put("specificationList", objectCallableTask.get());
            data.put("productList", productListCallableTask.get());
            data.put("attribute", goodsAttributeListTask.get());
            data.put("cartGoodsCount",lcartTask.get());
        }catch (Exception e){
            e.printStackTrace();
        }

        return ResponseUtil.ok(data);
    }

    @GetMapping("/queryUser")
    public Object queryUser(String mobile) {
        Map<String, Object> data = new HashMap<>();
        LitemallUser user =   userService.findByMobile(mobile);
        data.put("user", user);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/userinfo")
    public Object userinfo(Integer useId) {
        Map<String, Object> data = new HashMap<>();

        LitemallMechanismUser  user =  mechanismUserService.findById(useId);
        List<LitemallOrder> litemallOrders = orderService.query(useId);

        int dfk = 0;
        int dsh = 0;
        for(LitemallOrder l : litemallOrders){
            String orderStatus = l.getOrderStatus().toString();
            if("101".equals(orderStatus)){
                dfk++;
            }
            else if("301".equals(orderStatus)){
                dsh++;
            }
        }
        data.put("user", user);
        data.put("dfk", dfk);
        data.put("dsh", dsh);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/addordelete")
    public Object addordelete(Integer userId,Byte type,Integer valueId){
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        Boolean mtype = true;
        LitemallCollect collect = collectService.queryByTypeAndValue(userId, type,mtype,valueId);
        String handleType = null;
        if(collect != null){
            handleType = "delete";
            collectService.deleteById(collect.getId());
        }
        else{
            handleType = "add";
            collect = new LitemallCollect();
            collect.setUserId(userId);
            collect.setValueId(valueId);
            collect.setType(type);
            collect.setMechanismType(true);
            collect.setAddTime(LocalDateTime.now());
            collectService.add(collect);
        }
        Map<String, Object> data = new HashMap();
        data.put("type", handleType);
        return  ResponseUtil.ok(data);
    }

    @GetMapping("adcart")
    public Object adcart(Integer userId,Integer goodsId,Integer productId,Integer number){
        System.out.print(userId+"-----"+goodsId+"------"+productId);
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        LitemallProduct product = productService.findById(productId);
        System.out.println("=========="+product);
        System.out.println("-----------"+product.getPrice());

        LitemallGoods goods = goodsService.findById(goodsId);

        LitemallCart cart = new LitemallCart();

        List<LitemallCart> lcart = cartService.queryByUidGidPid(userId,goodsId,productId);

        String handleType = null;
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {
            if (lcart.size() != 0) {

                int newNum = lcart.get(0).getNumber() + number;
                cart.setNumber((short) newNum);
                cart.setId(lcart.get(0).getId());
                cart.setAddTime(LocalDateTime.now());
                cart.setPrice(product.getPrice());
                cartService.updateByIdtoNum(cart);
                handleType = "success";
            } else {
                cart.setUserId(userId);
                cart.setGoodsId(goodsId);
                cart.setGoodsSn(goods.getGoodsSn());
                cart.setGoodsName(goods.getName());
                cart.setProductId(product.getId());
                cart.setPrice(product.getPrice());
                cart.setDeleted(false);
                cart.setIntegral(product.getIntegral());
                cart.setNumber(Short.parseShort(Integer.toString(number)));
                cart.setSpecifications(product.getSpecifications());
                cart.setPicUrl(product.getUrl());
                cart.setAddTime(LocalDateTime.now());
                cartService.add(cart);
                handleType = "success";
            }
        }catch (Exception ex){
            txManager.rollback(status);
            handleType="false";
        }
        txManager.commit(status);
        Map<String, Object> data = new HashMap();
        data.put("message", handleType);

        return  ResponseUtil.ok(data);
    }

    @GetMapping("buynow")
    public Object buynow(Integer userId,Integer goodsId,Integer productId,Integer number){
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        LitemallProduct product = productService.findById(productId);

        LitemallGoods goods = goodsService.findById(goodsId);

        LitemallCart cart = new LitemallCart();

        cart.setUserId(userId);
        cart.setGoodsId(goodsId);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName(goods.getName());
        cart.setProductId(product.getId());
        cart.setPrice(product.getPrice());
        cart.setIntegral(product.getIntegral());
        cart.setNumber(Short.parseShort(Integer.toString(number)));
        cart.setSpecifications(product.getSpecifications());
        cart.setPicUrl(product.getUrl());
        cart.setAddTime(LocalDateTime.now());

        List<LitemallCart> lcart = new ArrayList<LitemallCart>();
        lcart.add(cart);
        Map<String, Object> result = new HashMap<>(16);

        result.put("cart",lcart);

        return  ResponseUtil.ok(result);
    }

    @GetMapping("/search")
    public Object search(Integer categoryId, Integer brandId, String kw, Integer isNew, Integer isHot,
         Integer userId,
         Integer page,
        Integer size,
        String sort, String order){
        String sortWithOrder = SortUtil.goodsSort(sort, order);
        List<LitemallGoods> data = goodsService.querySelective(categoryId, brandId, kw, isHot, isNew, page, size, sortWithOrder,SystemConfig.getCateGoryL2());

        return ResponseUtil.ok(data);
    }

    @GetMapping("/accountControl")
    public Object list(Integer id){
        LitemallMechanism mdList = mechanismService.findById(id);
        Map<String, Object> data = new HashMap<>();
        data.put("mdList", mdList);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/logout")
    public Object logout(HttpServletRequest request){
        request.getSession().invalidate();
        return ResponseUtil.ok();
    }

    /**
     * 订单信息
     * @param userId 用户ID
     * @param status 订单状态
     */
    @GetMapping("/order")
    public Object order(Integer userId, Integer status) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (status == null) {
            status = 0;
        }

        List<Short> orderStatus = OrderUtil.orderStatus(status);
        Boolean mtype = true;
        List<LitemallOrder> orderList = orderService.queryByOrderStatus(userId, orderStatus,mtype);

        List<Map<String, Object>> orderVoList = new LinkedList<>();
        for (LitemallOrder order : orderList) {
            Map<String, Object> orderVo = new HashMap<>();
            orderVo.put("id", order.getId());
            orderVo.put("orderSn", order.getOrderSn());
            orderVo.put("actualPrice", order.getActualPrice());
            orderVo.put("actualIntegral", order.getActualIntegral());

            orderVo.put("orderStatusText", OrderUtil.orderStatusText(order));
            orderVo.put("handleOption", OrderUtil.build(order));

            List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());
            List<Map<String, Object>> orderGoodsVoList = new LinkedList<>();
            for (LitemallOrderGoods orderGoods : orderGoodsList) {
                Map<String, Object> orderGoodsVo = new HashMap<>();
                orderGoodsVo.put("id", orderGoods.getId());
                orderGoodsVo.put("goodsName", orderGoods.getGoodsName());
                orderGoodsVo.put("number", orderGoods.getNumber());
                orderGoodsVo.put("picUrl", orderGoods.getPicUrl());
                orderGoodsVoList.add(orderGoodsVo);
            }
            orderVo.put("goodsList", orderGoodsVoList);

            orderVoList.add(orderVo);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("data", orderVoList);
        return ResponseUtil.ok(data);
    }

    /**
     * 订单详细信息
     * @param userId 用户ID
     * @param orderId 订单ID
     */
    @GetMapping("orderDetail")
    public Object orderDetail(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        // 订单信息
        LitemallOrder order = orderService.findById(orderId);
        if (null == order) {
            return ResponseUtil.fail(403, "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.fail(403, "不是当前用户的订单");
        }
        Map<String, Object> orderVo = new HashMap<String, Object>();
        orderVo.put("id", order.getId());
        orderVo.put("orderSn", order.getOrderSn());
        orderVo.put("addTime", order.getAddTime());
        orderVo.put("consignee", order.getConsignee());
        orderVo.put("mobile", order.getMobile());
        orderVo.put("address", order.getAddress());
        orderVo.put("goodsPrice", order.getGoodsPrice());
        orderVo.put("freightPrice", order.getFreightPrice());
        orderVo.put("actualPrice", order.getActualPrice());
        orderVo.put("actualIntegral", order.getActualIntegral());

        orderVo.put("orderStatusText", OrderUtil.orderStatusText(order));
        orderVo.put("handleOption", OrderUtil.build(order));
        orderVo.put("expCode", order.getShipChannel());
        orderVo.put("expNo", order.getShipSn());
        orderVo.put("orderStatus", order.getOrderStatus());

        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());
        List<Map<String, Object>> orderGoodsVoList = new ArrayList<>(orderGoodsList.size());
        Boolean first = true;
        Boolean second = false;
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            Map<String, Object> orderGoodsVo = new HashMap<>();
            orderGoodsVo.put("id", orderGoods.getId());
            orderGoodsVo.put("orderId", orderGoods.getOrderId());
            orderGoodsVo.put("goodsId", orderGoods.getGoodsId());
            orderGoodsVo.put("goodsName", orderGoods.getGoodsName());
            orderGoodsVo.put("number", orderGoods.getNumber());
            orderGoodsVo.put("retailPrice", orderGoods.getPrice());
            orderGoodsVo.put("retailIntegral", orderGoods.getIntegral());

            int orderStatus = orderService.findById(orderId).getOrderStatus();
            System.out.println(orderStatus);
            if (orderStatus != 0 && (orderStatus == 401 || orderStatus == 402 || orderStatus == 501)) {
                //只有在收货之后,才可以评价；用户评价一次之后可以评价订单里面的其他商品501
                orderGoodsVo.put("commentsStatus", first);
                orderGoodsVo.put("commentsStatused", second);
            } else {

                orderGoodsVo.put("commentsStatus", second);
                orderGoodsVo.put("commentsStatused", second);
            }

            if (orderGoods.getCommentsStatus() != null && orderGoods.getCommentsStatus() != 0) {
                int commentsStatus = orderGoods.getCommentsStatus();

                if (commentsStatus == 501) {
                    orderGoodsVo.put("orderGoodsCommentsStatus", "已评价");
                    orderGoodsVo.put("commentsStatused", first);
                    orderGoodsVo.put("commentsStatus", second);

                } else if (commentsStatus == 502) {
                    orderGoodsVo.put("orderGoodsCommentsStatus", "已追评");

                    orderGoodsVo.put("commentsStatus", second);
                    orderGoodsVo.put("commentsStatused", second);
                } else {
                    orderGoodsVo.put("orderGoodsCommentsStatus", "");
                    orderGoodsVo.put("commentsStatus", first);
                    orderGoodsVo.put("commentsStatused", second);

                }
            }

            orderGoodsVo.put("integralFlag", orderGoods.getIntegralFlag());
            orderGoodsVo.put("priceFlag", orderGoods.getPriceFlag());

            orderGoodsVo.put("picUrl", orderGoods.getPicUrl());
            orderGoodsVo.put("goodsSpecificationValues", orderGoods.getSpecifications());
            orderGoodsVoList.add(orderGoodsVo);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("orderInfo", orderVo);
        data.put("orderGoods", orderGoodsVoList);
        return ResponseUtil.ok(data);

    }

    /**
     * 取消订单
     * @param userId 用户ID
     * @param orderId 订单ID
     */
    @GetMapping("cancelOrder")
    public Object cancelOrder(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.findById(orderId);
        if (order == null) {
            return ResponseUtil.badArgumentValue();
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        // 检测是否能够取消
        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isCancel()) {
            return ResponseUtil.fail(403, "订单不能取消");
        }

        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {
            // 设置订单已取消状态
            order.setOrderStatus(OrderUtil.STATUS_CANCEL);
            order.setEndTime(LocalDateTime.now());
            orderService.update(order);

            // 商品货品数量增加
            List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
            for (LitemallOrderGoods orderGoods : orderGoodsList) {
                Integer productId = orderGoods.getProductId();
                LitemallProduct product = productService.findById(productId);
                Integer number = product.getNumber() + orderGoods.getNumber();
                product.setNumber(number);
                productService.updateById(product);
            }
        }
        catch (Exception ex) {
            txManager.rollback(status);
            return ResponseUtil.fail(403, "订单取消失败");
        }
        txManager.commit(status);

        return ResponseUtil.ok();
    }

    private String createRecordSn() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String dateStr = sdf.format(date);
        String res = (int)Math.ceil(Math.random() * 1000) + "";
        return dateStr + res;
    }

    /**
     * 确认收货
     * @param userId 用户ID
     * @param orderId 订单ID
     */
    @GetMapping("confirmOrder")
    public Object confirmOrder(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.findById(orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isConfirm()) {
            return ResponseUtil.fail(403, "订单不能确认收货");
        }
        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);

        try {
            order.setOrderStatus(OrderUtil.STATUS_CONFIRM);
            order.setConfirmTime(LocalDateTime.now());
            orderService.update(order);

            //添加钱包的记录
            LitemallWalletRecord walletRecord = new LitemallWalletRecord();
            LocalDateTime nowTime = LocalDateTime.now();
            String recordSn = this.createRecordSn();
            walletRecord.setUserId(userId);
            walletRecord.setRecordSn(recordSn);
            walletRecord.setType(new Byte("2"));
            walletRecord.setPayId(recordSn);
            walletRecord.setPayTime(nowTime);
            walletRecord.setModifyTime(nowTime);
            walletRecord.setModifyReason("消费");
            walletRecordService.add(walletRecord);
            txManager.commit(status);
        }
        catch (Exception e) {
            txManager.rollback(status);
            e.printStackTrace();
        }

        return ResponseUtil.ok();
    }

    /**
     * 退款
     * @param userId 用户ID
     * @param orderId 订单ID
     */
    @GetMapping("exchangeOrder")
    public Object exchangeOrder(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.findById(orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isRefund()) {
            return ResponseUtil.fail(403, "订单不能取消");
        }

        // 设置订单申请退款状态
        order.setOrderStatus(OrderUtil.STATUS_REFUND);
        orderService.update(order);

        // 发送邮件和短信通知，这里采用异步发送
        // 有用户申请退款，邮件通知运营人员
        notifyService.notifyMail("退款申请", order.toString());

        return ResponseUtil.ok();
    }

    /**
     * 添加用户openid
     */
    @GetMapping("/addUserOpen")
    public Object addUserOpen(String  code) {
        JSONObject jsonObject =null;//处理微信返回json数据
        String openid="";//微信用户openid
        String access_token="";//授权码
        String resultStr ="";//接口返回字符

        String requesUrl = Configure.WX_GET_ACCESS_URL;//获取openid地址
        String userinfoUrl= Configure.WX_GET_USER_INFO_URL;//拉取用户信息地址
        Map<String, Object> data = new HashMap<>();
        try {
            if(!StringUtils.isBlank(code)&&!StringUtils.isBlank(requesUrl)){//开始获取用户openid
                requesUrl = requesUrl.replace("APP_ID",Configure.APP_ID).replace("APP_SECRET",Configure.APP_SECRET).replace("USE_CODE", code);
                resultStr = HttpsUtil.httpsRequest(requesUrl, "GET", null);//调用获取openid接口
                if(!StringUtils.isBlank(resultStr)&&resultStr.indexOf("openid")>0){
                    jsonObject = JSONObject.parseObject(resultStr);
                    openid=jsonObject.get("openid").toString();
                }
            }
        } catch (Exception e) {

        }
        LitemallMechanismUser   user = mechanismUserService.queryByOpenId(openid);
        if(user == null){
            data.put("openid", openid);
            data.put("userinfo", "");
        }else{
            data.put("userinfo", user);
            data.put("openid", openid);
        }
        return ResponseUtil.ok(data);
    }


    /**
     * 添加用户openid
     */
    @GetMapping("/loginout")
    public Object loginout(Integer  id) {
        LitemallMechanismUser   user = mechanismUserService.findById(id);
        user.setOpenId("");
        mechanismUserService.update(user);
        return ResponseUtil.ok( );
    }

    /**
     * 添加用户
     */
    @GetMapping("/addUser")
    public Object addUser(String mobile,Byte sex,String username,Integer mechanismid) {
        LitemallUser userCheck = userService.findByMobile(mobile);
        if(userCheck == null) {
            LitemallUser user = new LitemallUser();
            user.setAddTime(LocalDateTime.now());
            String password = CharUtil.getRandomNum(6);
            String payPassword = CharUtil.getRandomNum(6);
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode(password);
            String encodedPayPassword = encoder.encode(payPassword);
            user.setPassword(encodedPassword);
            user.setPayPassword(encodedPayPassword);
            user.setMobile(mobile);
            user.setFirstMechanism(mechanismid);
            user.setUsername(username);
            user.setGender(sex);
            userService.add(user);
            //发送短信通知
            String params = new String("{\"username\":\"" + user.getUsername() + "\",\"password\":\"" + password + "\",\"paypassword\":\"" + payPassword + "\"}");
            notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.CREATEUSER, params);
            return ResponseUtil.ok(user);
        }else{
            return ResponseUtil.ok("fail");
        }
//        return ResponseUtil.ok( );
    }


    @GetMapping("submit")
    public Object submit(String number, String productIds, Integer userId,String name,String mobile,String address, BigDecimal actualPrice,String mtypeStr,Integer addressId,String goodsIds) throws Exception {
        Integer orderId;
        System.out.println(goodsIds+"goodsids");
        List<String> checkedGoodsId = java.util.Arrays.asList(goodsIds.substring(0, goodsIds.length() - 2).split("@@"));
        List<String> checkedProductId = java.util.Arrays.asList(productIds.substring(0, productIds.length() - 2).split("@@"));
        List<String> numbers = java.util.Arrays.asList(number.substring(0, number.length() - 2).split("@@"));
        System.out.println(checkedProductId+"checkproductid");
        Map<String, Object> data = new HashMap<>(16);
//        //解密
//        DesNoViUtil tools = new DesNoViUtil();
        LitemallAddress checkedAddress = addressService.findById(addressId);
      String orderSn =  orderService.generateOrderSn(userId);
        LitemallOrder order=null;
        order = new LitemallOrder();
        order.setUserId(userId);
        order.setOrderSn(orderSn);
        order.setAddTime(LocalDateTime.now());
        order.setOrderStatus(OrderUtil.STATUS_CREATE);
        order.setConsignee(name);
        order.setMobile(mobile);
        String detailedAddress = detailedAddress(checkedAddress);
        order.setAddress(detailedAddress);



        //TODO 修改订单信息 价格等
        // 机构标志 true 为机构，false则不是
        Boolean mType;
        if("false".equals(mtypeStr)){
            mType=false;
        }else {
            mType = true;
        }
        order.setGoodsPrice(actualPrice);
        order.setActualPrice(actualPrice);
        order.setActualIntegral(0);
        order.setMechanismType(mType);
        //TODO 添加订单表项
        orderService.add(order);
        orderId = order.getId();
        LitemallOrderGoods orderGoods = new LitemallOrderGoods();

        List<Integer> productides = new ArrayList<>();
        for(int i = 0; i < checkedGoodsId.size(); i++){
            orderGoods.setOrderId(orderId);
            Integer goodsId = Integer.parseInt(checkedGoodsId.get(i));
            orderGoods.setGoodsId(goodsId);
            LitemallGoods goods = goodsService.findById(goodsId);
            orderGoods.setGoodsName(goods.getName());
            orderGoods.setGoodsSn(goods.getGoodsSn());

            Integer productId = Integer.parseInt(checkedProductId.get(i));
            productides.add(productId);
            orderGoods.setProductId(productId);
            short num = Short.parseShort(numbers.get(i));
            orderGoods.setNumber(num);
            orderGoods.setPrice(goods.getRetailPrice());
            orderGoods.setIntegral(goods.getIntegral());
            LitemallProduct product = productService.findById(productId);
            orderGoods.setSpecifications(product.getSpecifications());
            orderGoods.setPicUrl(goods.getPicUrl());
            orderGoods.setAddTime(LocalDateTime.now());
            Byte a = 1;
            orderGoods.setIntegralFlag(a);
            orderGoods.setPriceFlag(a);
            orderGoodsService.add(orderGoods);
        }
        // 删除购物车信息
        System.out.println(productides+"addasdfafd");
        cartService.delete(productides,userId);

        data.put("orderStatus", order.getOrderStatus());
        data.put("orderId", orderId);
        data.put("orderSn", orderSn);
        return ResponseUtil.ok(data);
    }

    private String detailedAddress(LitemallAddress litemallAddress) {
        List<LitemallRegion> regionList = getLitemallRegions();
        Integer provinceId = litemallAddress.getProvinceId();
        Integer cityId = litemallAddress.getCityId();
        Integer areaId = litemallAddress.getAreaId();
        String provinceName= regionList.stream().filter(region->region.getId().equals(provinceId)).findAny().orElse(null).getName();
        String cityName =regionList.stream().filter(region->region.getId().equals(cityId)).findAny().orElse(null).getName();
        String areaName =regionList.stream().filter(region->region.getId().equals(areaId)).findAny().orElse(null).getName();
        String fullRegion = provinceName + " " + cityName + " " + areaName;
        return fullRegion + " " + litemallAddress.getAddress();
    }
}


